package im.engure.common.server.netty.handler;

import im.engure.common.protocol.Invocation;
import im.engure.common.registery.LocalServiceRegistry;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;
import java.util.Arrays;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        Invocation invocation = (Invocation) msg;
        Class<?> serviceImplClazz = LocalServiceRegistry.getServiceImpl(invocation.getInterfaceName());
        Method method = serviceImplClazz.getMethod(invocation.getMethodName(), invocation.getParamTypes());
        Object instance = serviceImplClazz.newInstance();

        Object result = method.invoke(instance, invocation.getParams());

        System.out.println("方法调用【" + invocation.getInterfaceName() + "】.【" +
                invocation.getMethodName() + "】，参数列表为【" +
                Arrays.toString(invocation.getParams()) + "】，结果为【" + result + "】");

        ctx.writeAndFlush(result);
    }
}
